package com.hnichr.ump.assessment.auth;

import com.hnichr.ump.common.assessment.entity.TenantUser;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.*;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.entity.User;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Component
public class TenantDataScapeProvider implements DataScapeProvider {

    private static final Logger logger = LoggerFactory.getLogger(TenantDataScapeProvider.class);

    @Override
    @Transactional(readOnly = true)
    public List<Criterion> provide() {
        List<Criterion> criterionList = new ArrayList<>();
        User user = SecurityUtils.getLoginUser();
        if(user.isAdministrator()){
            logger.info(">>>>>>>>>>>>>>>>>administrator ignore dataauth");
            return criterionList;
        }
        List<TenantUser> tenantUserList = JpaUtil.linq(TenantUser.class).equal("userName",user.getUsername()).list();
        if(CollectionUtils.isEmpty(tenantUserList)){
            SimpleCriterion criterion = new SimpleCriterion("id",Operator.EQ,"null");
            criterionList.add(criterion);
            return criterionList;
        }
        Junction junction  = new Junction(JunctionType.OR);
        for(TenantUser tenantUser:tenantUserList){
            junction.addCriterion("tenantId", Operator.EQ,tenantUser.getTenantId());
        }
        criterionList.add(junction);
        return criterionList;
    }
}
